package io.joern.scanners.c

import io.joern.scanners.*
import io.joern.console.*
import io.joern.macros.QueryMacros.*
import io.shiftleft.semanticcpg.language.*

object GJB_8114_R_1_13_1 extends QueryBundle {

  implicit val resolver: ICallResolver = NoResolve

  @q
  def R_1_13_1(): Query =
    Query.make(
      name = "R_1_13_1",
      author = Crew.Sixpence,
      title = "禁止局部变量与全局变量同名.",
      description = """
                      |当局部变量与全局变量同名时，局部变量会覆盖全局变量，导致全局变量在函数内部无法直接访问。
                     """.stripMargin,
      score = 2,
      withStrRep({ cpg =>
        val globalVariableNames = cpg.method.internal.name("<global>").flatMap(_.local).map(_.name).toList
        cpg.method
          .filter(m => m.code != "<empty>" && m.code != "<global>")
          .local
          .filter(x => globalVariableNames.contains(x.name))
      }),
      tags = List(QueryTags.default),
      codeExamples = CodeExamples(
        List("""
               |
               |int sign = 100;
               |
               |void func() {
               |    int local = 0;
               |    int sign = 0; //violation
               |}
               |""".stripMargin),
        List("""
               |
               |int sign = 100;
               |
               |void func() {
               |    int local_sign = 0; //ok
               |}
               |""".stripMargin)
      )
    )
}
